var rpc = null;
var game_manager = null;
var test = null;
var last_exit_time = 0;


function connect() {
	rpc = new RPC();
	var username = $('#username').val(), ip = $('#ip').val(), port;
	if(12 < username.length || username.length < 3) {
		alert("Username: max 12, min 3");
		return
	}
	port = parseInt($('#port').val());
	if ($('#port').val().length == 0 || isNaN(port)) {
		alert("Invalid port number!");
	}
	
	rpc.subscribe_logged_in(connected);
	rpc.connect(ip, port, username);

};

function connected() {
	console.log("Yep, connected");
	$('#screen_login').hide();
	$('#screen_game_menu').show();
	game_manager = new GameManager(rpc);
	game_manager.start();
};

function end_game() {
	if(game_manager) {
		game_manager.stop();
	}
	game_manager.close_all_screens();
	$('#screen_game_menu').show();
}

function start_swipe() {
	$('#screen_login').hide();
	test = new GameSwipe(null);
	test.start(false);
	test.show();
};

function send_ready() {
	rpc.subscribe_end_game(end_game);
	rpc.send_ready();
	document.addEventListener("backbutton", on_back_button, false);
};

function on_back_button() {
	var current_timestamp = new Date().getTime();
	if(current_timestamp - last_exit_time < 1000) {
		// events will do the rest
		rpc.disconnect();
		game_manager.close_all_screens();
		$('#screen_login').show();
	} else {
		last_exit_time = current_timestamp;
	}

};


function read_qrcode() {
	window.plugins.barcodeScanner.scan(function(result) {
		var qr = result.text;
		if(qr) {
			qr_split = qr.split(";");
			if(qr_split.length > 1) {
				$('#port').val(qr_split[0]);
				$('#ip').val(qr_split[1]);
			}
		}
	}, function(error) {
		alert("Scan failed: " + error);
	});
};

function exit() {
	 navigator.app.exitApp();
};

function show_about() {
	game_manager.close_all_screens();
	$('#screen_about').show();
	document.addEventListener("backbutton", back_to_menu, false);
}

function back_to_menu() {
	game_manager.close_all_screens();
	$('#screen_game_menu').show();
}

